package org.openmore.opc.service.impl;

import org.openmore.opc.entity.enums.TenantStatus;
import org.openmore.opc.framework.ReferencedFieldProcessor;
import org.openmore.opc.service.TenantService;

import org.openmore.opc.entity.Tenant;
import org.openmore.opc.dao.TenantMapper;
import org.openmore.opc.dto.api.TenantDto;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import com.github.pagehelper.Page;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import org.openmore.common.exception.OpenmoreException;
import org.springframework.util.StringUtils;
import java.util.List;

@Service
public class TenantServiceImpl extends BaseServiceImpl implements TenantService{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private TenantMapper tenantMapper;


    @Autowired
    private ReferencedFieldProcessor processor;

    /**
     * 将实体list转成带有分页的PageList
     * @return
     */
    private TenantDto convertFrom(Tenant entity) {
        if (null == entity) {
            return null;
        }
        TenantDto dto = new TenantDto();
        BeanUtils.copyProperties(entity, dto);
        processor.processOne(dto);
        return dto;
    }
    /**
     * 将实体list转成带有分页的PageList
     * @return
     */
    private Page<TenantDto> convertFrom(List<Tenant> entitiesList) {
        Page<TenantDto> dtoPageList = new Page<>();
        if (entitiesList instanceof Page) {
            BeanUtils.copyProperties(entitiesList, dtoPageList);
            dtoPageList.clear();
        }

        for (Tenant en : entitiesList) {
            TenantDto dto = new TenantDto();
            BeanUtils.copyProperties(en, dto);
            dtoPageList.add(dto);
        }
//        List<TenantDto> dtoList = dtoPageList.getResult();
        processor.process(dtoPageList);
        return dtoPageList;
    }
    /**
     * 根据id获得实体对象
     * @param id
     */
    @Override
    public Tenant getEntityById(String id) {
        Example example = new Example(Tenant.class);
        example.createCriteria().andEqualTo("id", id).andEqualTo("deleted", false);
        return tenantMapper.selectOneByExample(example);
    }

    /**
     * 根据id获得DTO对象
     * @param id
     */
    @Override
    public TenantDto getDtoById(String id) {
        TenantDto dto = new TenantDto();
        Tenant tenant = this.getEntityById(id);
        if (tenant == null){
            return null;
        }
        BeanUtils.copyProperties(tenant, dto);
        processor.processOne(dto);
        return dto;
    }

    /**
     * 获得所有记录
     * @return
     */
    @Override
    public List<TenantDto> selectAll(String userId, String name, TenantStatus status, Date createTimeStart, Date createTimeEnd) {
        Example example = new Example(Tenant.class);
         Example.Criteria criteria = example.createCriteria().andEqualTo("deleted", false);
         if(!StringUtils.isEmpty(userId)){
             criteria.andEqualTo("userId", userId);
         }
         if(!StringUtils.isEmpty(name)){
             name = "%" + name + "%";
             criteria.andLike("name", name);
         }
         if(null != status){
             criteria.andEqualTo("status", status);
         }
         if(null!=createTimeStart && null != createTimeEnd){
             if(createTimeEnd.before(createTimeStart)){
                 createTimeEnd = createTimeStart;
             }
         }
         if(null != createTimeStart){
             criteria.andGreaterThanOrEqualTo("createdTime", createTimeStart);
         }
         if(null != createTimeEnd){
             criteria.andLessThanOrEqualTo("createdTime", createTimeEnd);
         }
         example.orderBy("createdTime").desc();
        List<Tenant> entityList =  tenantMapper.selectByExample(example);
        insertLog("查询Tenant列表");
        return convertFrom(entityList);
    }

    @Override
    public Integer selectCount(String userId, String name, TenantStatus status, Date createTimeStart, Date createTimeEnd){
        Integer count = 0;
        Example example = new Example(Tenant.class);
        Example.Criteria criteria = example.createCriteria().andEqualTo("deleted", false);
        if(!StringUtils.isEmpty(userId)){
            criteria.andEqualTo("userId", userId);
        }
        if(!StringUtils.isEmpty(name)){
            name = "%" + name + "%";
            criteria.andLike("name", name);
        }
        if(null != status){
            criteria.andEqualTo("status", status);
        }
        if(null!=createTimeStart && null != createTimeEnd){
            if(createTimeEnd.before(createTimeStart)){
                createTimeEnd = createTimeStart;
            }
        }
        if(null != createTimeStart){
            criteria.andGreaterThanOrEqualTo("createdTime", createTimeStart);
        }
        if(null != createTimeEnd){
            criteria.andLessThanOrEqualTo("createdTime", createTimeEnd);
        }
        count = tenantMapper.selectCountByExample(example);
        insertLog("查询Tenant列表数量");
        return null==count?0:count;
    }

    /**
     * 带UUID的插入
     * 所有的插入数据，都要调用这个实现
     * @param dto
     */
    @Override
    public TenantDto insert(TenantDto dto){
        if(null==dto){
        throw new OpenmoreException(400, "参数不能为空");
        }
        if(StringUtils.isEmpty(dto.getUserId())){
            throw new OpenmoreException(400, "创建者ID不能为空");
        }
        if(StringUtils.isEmpty(dto.getName())){
            throw new OpenmoreException(400, "名称不能为空");
        }
        List<TenantDto> oldList = selectAll(null, dto.getName(), TenantStatus.PASS_APPLY, null, null);
        if(!CollectionUtils.isEmpty(oldList)){
            throw new OpenmoreException("已存在同名应用");
        }
        Tenant entity = new Tenant();
        BeanUtils.copyProperties(dto, entity);
        beforeInsert(entity);
        entity.setStatus(TenantStatus.JUST_APPLY);
        tenantMapper.insert(entity);
        insertLog("插入Tenant项id:"+entity.getId());
        processor.processOne(dto);
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    /**
     * 删除指定id的数据
     */
    @Override
    public void deleteById(String id){
        if(StringUtils.isEmpty(id)){
        throw new OpenmoreException(400, "id不能为空");
        }
        Tenant entity = this.getEntityById(id);
        if (entity != null) {
            Example example = new Example(Tenant.class);
            example.createCriteria().andEqualTo("id", id).andEqualTo("deleted", false);
            entity.setDeleted(true);
            tenantMapper.updateByExampleSelective(entity, example);
            insertLog("删除Tenant项id:"+id);
        }
    }
    /**
     * 修改数据
    */
    @Override
    public void update(TenantDto dto){
        if (null == dto) {
        throw new OpenmoreException(400, "参数不能为空");
        }
        if(StringUtils.isEmpty(dto.getId())){
        throw new OpenmoreException(400, "id不能为空");
        }
        Tenant entity = new Tenant();
        BeanUtils.copyProperties(dto, entity);
        Example example = new Example(Tenant.class);
        example.createCriteria().andEqualTo("id", entity.getId()).andEqualTo("deleted", false);
        beforeUpdate(entity);
        tenantMapper.updateByExampleSelective(entity, example);
    }
}